package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.RandomUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.vo.AppOrderVo;
import org.dromara.system.domain.vo.AppProcurementPlanStaySendVo;
import org.dromara.system.domain.vo.UserVo;
import org.dromara.system.mapper.*;
import org.dromara.system.service.IAppUserService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.vo.AppDriverDetailVo;
import org.dromara.system.service.IAppDriverDetailService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 司机详情Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppDriverDetailServiceImpl implements IAppDriverDetailService {

    private final AppDriverDetailMapper baseMapper;
    private final IAppUserService appUserService;
    private final AppOrderMapper appOrderMapper;
    private final AppProcurementPlanMapper appProcurementPlanMapper;
    private final AppOrderServiceImpl appOrderService;
    private final AppQualityInfoMapper appQualityInfoMapper;
    private final AppProcurementDetailMapper appProcurementDetailMapper;
    private final AppWarehouseMapper appWarehouseMapper;
    private final AppWarehouseRecordMapper appWarehouseRecordMapper;
    private final AppMessageRemindMapper appMessageRemindMapper;

    /**
     * 查询司机详情
     *
     * @return 司机详情
     */
    @Override
    public AppDriverDetailVo queryById(String  phone){
        LambdaQueryWrapper<AppDriverDetail> appDriverDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appDriverDetailLambdaQueryWrapper.eq(AppDriverDetail::getDriverPhone, phone);
        return MapstructUtils.convert(baseMapper.selectOne(appDriverDetailLambdaQueryWrapper), AppDriverDetailVo.class);
    }

    /**
     * 分页查询司机详情列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 司机详情分页列表
     */
    @Override
    public TableDataInfo<AppDriverDetailVo> queryPageList(AppDriverDetailBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppDriverDetail> lqw = buildQueryWrapper(bo);
        Page<AppDriverDetailVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的司机详情列表
     *
     * @param bo 查询条件
     * @return 司机详情列表
     */
    @Override
    public List<AppDriverDetailVo> queryList(AppDriverDetailBo bo) {
        LambdaQueryWrapper<AppDriverDetail> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppDriverDetail> buildQueryWrapper(AppDriverDetailBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppDriverDetail> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppDriverDetail::getId);
        lqw.eq(bo.getUserId() != null, AppDriverDetail::getUserId, bo.getUserId());
        lqw.eq(bo.getIdentityType() != null, AppDriverDetail::getIdentityType, bo.getIdentityType());
        lqw.eq(bo.getStatus() != null, AppDriverDetail::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getTransportCompany()), AppDriverDetail::getTransportCompany, bo.getTransportCompany());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyScale()), AppDriverDetail::getCompanyScale, bo.getCompanyScale());
        lqw.eq(StringUtils.isNotBlank(bo.getTaxpayerId()), AppDriverDetail::getTaxpayerId, bo.getTaxpayerId());
        lqw.like(StringUtils.isNotBlank(bo.getContactName()), AppDriverDetail::getContactName, bo.getContactName());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPhone()), AppDriverDetail::getContactPhone, bo.getContactPhone());
        lqw.like(StringUtils.isNotBlank(bo.getDriverName()), AppDriverDetail::getDriverName, bo.getDriverName());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverIdCard()), AppDriverDetail::getDriverIdCard, bo.getDriverIdCard());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverPhone()), AppDriverDetail::getDriverPhone, bo.getDriverPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getTruckFrontPhoto()), AppDriverDetail::getTruckFrontPhoto, bo.getTruckFrontPhoto());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonalPhoto()), AppDriverDetail::getPersonalPhoto, bo.getPersonalPhoto());
        lqw.eq(StringUtils.isNotBlank(bo.getDrivingLicensePhoto()), AppDriverDetail::getDrivingLicensePhoto, bo.getDrivingLicensePhoto());
        lqw.eq(StringUtils.isNotBlank(bo.getVehicleLicensePhoto()), AppDriverDetail::getVehicleLicensePhoto, bo.getVehicleLicensePhoto());
        lqw.eq(StringUtils.isNotBlank(bo.getCarPlate()), AppDriverDetail::getCarPlate, bo.getCarPlate());
        lqw.eq(StringUtils.isNotBlank(bo.getCarType()), AppDriverDetail::getCarType, bo.getCarType());
        lqw.eq(bo.getCarLength() != null, AppDriverDetail::getCarLength, bo.getCarLength());
        lqw.eq(bo.getLoadCapacity() != null, AppDriverDetail::getLoadCapacity, bo.getLoadCapacity());
        return lqw;
    }

    /**
     * 新增司机详情
     *
     * @param bo 司机详情
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppDriverDetailBo bo) {
        //验证码校验
        AppDriverDetail add = MapstructUtils.convert(bo, AppDriverDetail.class);
        validEntityBeforeSave(add);
        if (add!=null){
            add.setStatus(0L);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            //生成用户数据
            AppUserBo appUserBo = new AppUserBo();
            appUserBo.setUserName(add.getDriverName());
            appUserBo.setPhone(add.getDriverPhone());
            appUserBo.setNickName(add.getDriverName());
            appUserBo.setRoleId(3L);
            appUserService.insertByBo(appUserBo);
            //绑定用户与司机的关系
            LambdaUpdateWrapper<AppDriverDetail> appDriverDetailLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            appDriverDetailLambdaUpdateWrapper.eq(AppDriverDetail::getDriverPhone,add.getDriverPhone());
            appDriverDetailLambdaUpdateWrapper.set(AppDriverDetail::getUserId,appUserBo.getId());
            baseMapper.update(add,appDriverDetailLambdaUpdateWrapper);
        }
        return flag;
    }

    /**
     * 修改司机详情
     *
     * @param bo 司机详情
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppDriverDetailBo bo) {
        AppDriverDetail update = MapstructUtils.convert(bo, AppDriverDetail.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppDriverDetail entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除司机详情信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized R<Void> grabOrder(AppDriverDetailBo bo) {
        Long userId = LoginHelper.getUserId();
        String orderId = bo.getOrderId();
        UserVo userVo = appUserService.queryByIdUserVo(userId);
        //如果不是司机 无法抢单
        if (userVo.getRoleId() != 3) {
            return R.fail("非司机无法抢单");
        }

        // 1. 查询订单
        AppOrder appOrder = appOrderMapper.selectOne(new LambdaQueryWrapper<AppOrder>().eq(AppOrder::getOrderId, orderId));
        if (appOrder == null) {
            return R.fail("订单不存在");
        }

        // 2. 判断订单是否已被抢
        if (appOrder.getDriverId() != null) {
            return R.fail("订单已被抢");
        }

        // 3. 加行锁再查一次，防止并发
        AppOrderVo lockedOrder = appOrderService.queryByIdForUpdate(orderId);
        if (lockedOrder == null) {
            return R.fail("订单不存在");
        }
        if (lockedOrder.getDriverId() != null) {
            return R.fail("订单已被抢");
        }

        // 4. 业务处理：更新订单司机信息
        lockedOrder.setDriverPhone(userVo.getPhoto());
        lockedOrder.setDriverName(userVo.getUserName());
        lockedOrder.setOrderId(orderId);
        lockedOrder.setDriverId(userId);
        //查自己司机信息
        AppDriverDetail appDriverDetail = baseMapper.selectOne(new LambdaQueryWrapper<AppDriverDetail>().eq(AppDriverDetail::getUserId, userId));
        if (appDriverDetail == null){
            return R.fail("司机信息不存在");
        }
        lockedOrder.setOrderStatus(2L);
        lockedOrder.setCarPlate(appDriverDetail.getCarPlate());
        lockedOrder.setCarType(appDriverDetail.getCarType());
        lockedOrder.setCarLength(appDriverDetail.getCarLength());
        lockedOrder.setLoadCapacity(appDriverDetail.getLoadCapacity());
        boolean update = appOrderService.updateGrabOrder(lockedOrder);

        if (!update) {
            return R.fail("抢单失败，请稍后重试");
        }

        // 5. 其他业务逻辑，比如推送消息给乘客
        // messageService.notifyPassenger(lockedOrder);

        return R.ok();
    }

    @Override
    public R<Void> carrier(AppDriverSureCarBo bo) {
        //承运之后状态 变为待发货
        LambdaQueryWrapper<AppOrder> ao = new LambdaQueryWrapper<>();
        ao.eq(AppOrder::getOrderId,bo.getOrderId());
        ao.eq(AppOrder::getDriverId,LoginHelper.getUserId());
        AppOrder appOrder = appOrderMapper.selectOne(ao);

        String planId = appOrder.getPlanId();
        AppProcurementPlan appPlan = appProcurementPlanMapper.selectOne(new LambdaQueryWrapper<AppProcurementPlan>().eq(AppProcurementPlan::getPlanCode, planId));
        if (appPlan!=null){
            appPlan.setStayCarrier(1);
            appProcurementPlanMapper.updateById(appPlan);
        }

        if (appOrder==null){
            return R.fail("订单不存在");
        }
        if (appOrder.getStayCarrier()==1){
            return R.fail("订单已承运");
        }

        //查询司机信息
        AppDriverDetail appDriverDetail = baseMapper.selectOne(new LambdaQueryWrapper<AppDriverDetail>().eq(AppDriverDetail::getUserId, appOrder.getDriverId()));
        if (appDriverDetail!=null){
            appOrder.setCarPlate(appDriverDetail.getCarPlate());
            appOrder.setTransportCompany(appDriverDetail.getTransportCompany());
            appOrder.setTaxpayerId(appDriverDetail.getTaxpayerId());
            appOrder.setContactName(appDriverDetail.getContactName());
            appOrder.setContactPhone(appDriverDetail.getContactPhone());
        }

        appOrder.setStayCarrier(1);
        //承运之后修改状态待发货
        appOrder.setOrderStatus(3L);
        appOrder.setRemark(bo.getRemark());
        appOrder.setLength(bo.getLength());
        appOrder.setWidth(bo.getWidth());
        appOrder.setHeight(bo.getHeight());
        appOrder.setCarLength(bo.getCarLength());
        appOrder.setCarType(bo.getCarType());
        appOrderMapper.updateById(appOrder);
        return R.ok();
    }

    @Override
    public R<Void> shipment(AppDriverSureSendBo bo) {
        //确认发货
        LambdaQueryWrapper<AppOrder> ao = new LambdaQueryWrapper<>();
        Long userId = LoginHelper.getUserId();
        ao.eq(AppOrder::getOrderId,bo.getOrderId());
        ao.eq(AppOrder::getDriverId,userId);
        AppOrder appOrder = appOrderMapper.selectOne(ao);
        if (appOrder==null){
            return R.fail("订单不存在");
        }
        appOrder.setOrderStatus(4L);
        appOrder.setRemark(bo.getRemark());
        appOrder.setPhotoLoadInfo(bo.getSendImage());
        appOrderMapper.updateById(appOrder);
        return R.ok();
    }

    @Override
    public R<Void> arrive(String orderId,String imgUrl) {
        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appOrderLambdaQueryWrapper.eq(AppOrder::getOrderId,orderId);
        AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
        if (appOrder==null){
            return R.fail("订单不存在");
        }
        //看订单是否在运输中
        if (appOrder.getOrderStatus()!=4){
            return R.fail("订单不在运输中");
        }
        appOrder.setOrderStatus(5L);
        appOrder.setPhotoUnloadInfo(imgUrl);
        appOrderMapper.updateById(appOrder);
        //推送消息给仓库管理员 等待入库！
        AppMessageRemind appMessageRemind = new AppMessageRemind();
        appMessageRemind.setPlanCode(appOrder.getPlanId());
        appMessageRemind.setRemindUser(appOrder.getWarehouseAdmin());
        appMessageRemind.setRoleId(4);
        appMessageRemind.setRemark("等待入库！");
        appMessageRemindMapper.insert(appMessageRemind);
        return R.ok();
    }

    @Override
    public R<Void> qualityInspectionSubmit(AppQualityInfoBo bo) {
        AppQualityInfo appQualityInfo = new AppQualityInfo();
        appQualityInfo.setOrderId(bo.getOrderId());
        appQualityInfo.setSampleWeight(bo.getSampleWeight());
        appQualityInfo.setPlasticContent(bo.getPlasticContent());
        appQualityInfo.setMoisture(bo.getMoisture());
        appQualityInfo.setAsh(bo.getAsh());
        appQualityInfo.setCarbon(bo.getCarbon());
        appQualityInfo.setHydrogen(bo.getHydrogen());
        appQualityInfo.setOxygen(bo.getOxygen());
        appQualityInfo.setNitrogen(bo.getNitrogen());
        appQualityInfo.setSulfur(bo.getSulfur());
        appQualityInfo.setFluorine(bo.getFluorine());
        appQualityInfo.setBromine(bo.getBromine());
        appQualityInfo.setQualityEvaluation(bo.getQualityEvaluation());
        appQualityInfo.setMaterialGrade(bo.getMaterialGrade());
        appQualityInfo.setVerificationNote(bo.getVerificationNote());
        appQualityInfo.setRemark(bo.getRemark());
        appQualityInfo.setInspector(bo.getInspector());
        appQualityInfo.setInspectionDate(bo.getInspectionDate());
        appQualityInfoMapper.insert(appQualityInfo);
        return R.ok();
    }

    @Override
    public R<Void> settlement(AppDriverDetailBo bo) {
        return R.fail("暂未开通支付模块");
//        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        appOrderLambdaQueryWrapper.eq(AppOrder::getOrderId,bo.getOrderId());
//        AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
//        if (appOrder==null){
//            return R.fail("订单不存在");
//        }
//        //看订单是否在运输中
//        if (appOrder.getOrderStatus()!=4){
//            return R.fail("订单不在运输中");
//        }
//        appOrder.setOrderStatus(5L);
//        appOrderMapper.updateById(appOrder);
//        return R.ok();
    }

    @Override
    public R<List<AppProcurementPlanStaySendVo>> staySend(AppOrderStaySendBo bo) {
        //查询待下发订单
        List<AppProcurementPlanStaySendVo> appProcurementPlanStaySendVos = new ArrayList<>();
        LambdaQueryWrapper<AppProcurementPlan> appUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appUserLambdaQueryWrapper.eq(AppProcurementPlan::getSentStatus,bo.getOrderStatus());
        List<AppProcurementPlan> appOrders = appProcurementPlanMapper.selectList(appUserLambdaQueryWrapper);
        if (CollUtil.isEmpty(appOrders)){
            return R.ok(appProcurementPlanStaySendVos);
        }

        List<AppProcurementPlanStaySendVo> collect = appOrders.stream().map(a -> {
            AppProcurementPlanStaySendVo ap = new AppProcurementPlanStaySendVo();
            ap.setId(a.getId());
            //采购编号
            ap.setPlanCode(a.getPlanCode());
            //公司id
            ap.setCompanyId(a.getCompanyId());
            //公司名称
            ap.setCompanyName(a.getCompanyName());
            ap.setCreateTime(a.getCreateTime());
            return ap;
        }).collect(Collectors.toList());

        if (StrUtil.isNotBlank(bo.getCompanyName())){
            collect = collect.stream().filter(a -> a.getCompanyName().contains(bo.getCompanyName())).collect(Collectors.toList());
        }

        //查询是否有订单号 存在的话赋值
        if (CollUtil.isNotEmpty(collect)){
            List<String> planList = collect.stream().map(AppProcurementPlanStaySendVo::getPlanCode).toList();
            //查询是否存在订单
            List<AppOrder> appOrdersPlan = appOrderMapper.selectList(new LambdaQueryWrapper<AppOrder>().in(AppOrder::getPlanId, planList));
            for (AppProcurementPlanStaySendVo appProcurementPlanStaySendVo : collect) {
                appOrdersPlan.stream().filter(a -> a.getPlanId().equals(appProcurementPlanStaySendVo.getPlanCode()))
                    .findFirst().ifPresent(a -> appProcurementPlanStaySendVo.setOrderId(a.getOrderId()));
            }
        }


        return R.ok(collect);
    }

    @Override
    public R<Void> sendSupplierOrder(AppOrderStaySendBo bo) {
        //查询采购计划
        LambdaQueryWrapper<AppProcurementPlan> ao = new LambdaQueryWrapper<>();
        ao.eq(AppProcurementPlan::getPlanCode,bo.getPlanCode());
        AppProcurementPlan appProcurementPlan = appProcurementPlanMapper.selectOne(ao);
        if (appProcurementPlan==null){
            return R.fail("订单不存在");
        }
        appProcurementPlan.setSentStatus(1);
        appProcurementPlanMapper.updateById(appProcurementPlan);


        //查询订单
        LambdaQueryWrapper<AppOrder> eq = new LambdaQueryWrapper<AppOrder>().eq(AppOrder::getPlanId, bo.getPlanCode());
        AppOrder appOrder = appOrderMapper.selectOne(eq);
        if (appOrder!=null){
            appOrder.setDeliveryAddress(bo.getDeliveryAddress());
            appOrder.setRemark(bo.getRemark());
            appOrder.setOrderStatus(1L);
            appOrderMapper.updateById(appOrder);
        }else {
            AppOrder appOrderIns = new AppOrder();
            appOrderIns.setDeliveryAddress(bo.getDeliveryAddress());
            appOrderIns.setRemark(bo.getRemark());
            appOrderIns.setPlanId(bo.getPlanCode());
            appOrderIns.setOrderStatus(1L);
            appOrderIns.setOrderId(RandomUtils.generateOrderId());
            appOrderMapper.insert(appOrder);
        }

        //推送消息给 物流专员 带确认！
        AppMessageRemind appMessageRemind = new AppMessageRemind();
        appMessageRemind.setPlanCode(bo.getPlanCode());
//        appMessageRemind.setRemindUser(2);
        appMessageRemind.setRoleId(6);
        appMessageRemind.setRemark("等待确认！");
        appMessageRemindMapper.insert(appMessageRemind);
        return R.ok();
    }

    @Override
    public R<Void> onlinePay(AppDriverSureCarBo bo) {
        //线上支付
        LambdaQueryWrapper<AppOrder> ao = new LambdaQueryWrapper<>();
        ao.eq(AppOrder::getOrderId,bo.getOrderId());
        AppOrder appOrder = appOrderMapper.selectOne(ao);
        if (appOrder==null){
            return R.fail("订单不存在");
        }
        appOrder.setOrderStatus(10L);
        appOrderMapper.updateById(appOrder);
        return R.ok();
    }

    @Override
    public R<Void> uploadReceivedOrder(AppOrderUploadBo bo) {
        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appOrderLambdaQueryWrapper.eq(AppOrder::getOrderId,bo.getOrderId());
        AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
        if (appOrder==null){
            return R.fail("订单不存在");
        }
        appOrder.setArrivalNotice(bo.getArrivalNotice());
        appOrder.setArrivalDate(bo.getArrivalDate());
        appOrderMapper.updateById(appOrder);

        //上传到收货单
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Void> warehouseEntry(AppOrderBo bo) {
        //入库
        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appOrderLambdaQueryWrapper.eq(AppOrder::getOrderId,bo.getOrderId());
        AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
        if (appOrder==null){
            return R.fail("订单不存在");
        }

        //根据订单查询采购详情
        LambdaQueryWrapper<AppProcurementDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailLambdaQueryWrapper.eq(AppProcurementDetail::getPlanCode,appOrder.getPlanId());
        List<AppProcurementDetail> appProcurementDetails = appProcurementDetailMapper.selectList(detailLambdaQueryWrapper);
        //查询仓库中数量
        LambdaQueryWrapper<AppWarehouse> warehouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        warehouseLambdaQueryWrapper.eq(AppWarehouse::getStoreId,appOrder.getWarehouseId() == null ? 1 : appOrder.getWarehouseId());
        List<AppWarehouse> appWarehouses = appWarehouseMapper.selectList(warehouseLambdaQueryWrapper);
        if (CollUtil.isEmpty(appWarehouses)){
            return R.fail("仓库不存在");
        }
        Map<Long, AppWarehouse> materMap = appWarehouses.stream().collect(Collectors.toMap(AppWarehouse::getMaterialId, appWarehouse -> appWarehouse));

        if (CollUtil.isNotEmpty(appProcurementDetails)){
            for (AppProcurementDetail appProcurementDetail : appProcurementDetails) {
                //原料id
                Long materialTypeId = appProcurementDetail.getMaterialTypeId();
                //吨数
                Long plannedWeight = appProcurementDetail.getPlannedWeight();
                //车数
                Long plannedTruckNum = appProcurementDetail.getPlannedTruckNum();
                //总吨数
                Long totalWeight = plannedWeight * plannedTruckNum;
                AppWarehouse appWarehouse = materMap.get(materialTypeId);
                if (appWarehouse==null){
                    continue;
                }
                appWarehouse.setStock(appWarehouse.getStock()+totalWeight);
                appWarehouseMapper.updateById(appWarehouse);
                //插入入库记录
                AppWarehouseRecord appWarehouseRecord = new AppWarehouseRecord();
                appWarehouseRecord.setStorageType(0L);
                appWarehouseRecord.setWarehouseId(appWarehouse.getStoreId());
                appWarehouseRecord.setWarehouseName(appWarehouse.getName());
                appWarehouseRecord.setLoadTotalWeight(totalWeight);
                appWarehouseRecord.setStorageQuantity(totalWeight);
                appWarehouseRecord.setPlanCode(appProcurementDetail.getPlanCode());
                //插入记录
                appWarehouseRecordMapper.insert(appWarehouseRecord);
            }
        }
        //入库完成后 变为已送达的状态
        BeanUtil.copyProperties(bo, appOrder, CopyOptions.create().ignoreNullValue());
        appOrder.setOrderStatus(5L);
        appOrder.setWarehouseCode(bo.getWarehouseId().toString());
        //设置仓库管理员
        appOrder.setWarehouseAdmin(LoginHelper.getUserId().toString());
        appOrderMapper.updateById(appOrder);

        //入库后推送消息给质检 待质检！
        AppMessageRemind appMessageRemind = new AppMessageRemind();
        appMessageRemind.setPlanCode(appOrder.getPlanId());
        appMessageRemind.setRoleId(5);
        appMessageRemind.setRemark("待质检！");
        appMessageRemindMapper.insert(appMessageRemind);

        return R.ok();
    }

    @Override
    public R<Void> returnOfGoods(AppOrderBo bo) {
        //退货
        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appOrderLambdaQueryWrapper.eq(AppOrder::getOrderId,bo.getOrderId());
        AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
        if (appOrder==null){
            return R.fail("订单不存在");
        }
        appOrder.setOrderStatus(12L);
        appOrderMapper.updateById(appOrder);

        return R.ok();
    }

    @Override
    public R<Void> setSinglePrice(String orderId, BigDecimal singlePrice) {
        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appOrderLambdaQueryWrapper.eq(AppOrder::getOrderId,orderId);
        AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
        if (appOrder!=null){
            appOrder.setUnitPrice(singlePrice);
            appOrderMapper.updateById(appOrder);
        }
        return R.ok();
    }
}
